<?php 

namespace Weixin\Controller;

use Common\Controller\WeixinBase;
use Think\Yfimage;

class WeixinbaseController extends WeixinBase 
{
	protected $openid = Null;
	protected $userid = 0;
	protected $appid = Null;
	protected $appsecret = Null;
	
	protected function _initialize() {
		parent::_initialize();
	
		$config = cache('Config');
		$this->appid = $config['wxappid'];
		$this->appsecret = $config['wxappsecret'];
		$userInfo = $this->getUserInfo();
		//$this->get_user_openid();
	}
	
	final public function get_user_openid()
	{
		$this->openid = $_SESSION['openid'];
		if(!$this->openid)
		{
			$openid = $this->get_baseinfo();
		}
	}
	
	final public function get_baseinfo()
	{
		if(!isset($_GET['code']))
		{
			$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			$url = $this->parseurl($url);
			header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$url.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect');
		}
		else
		{
			
		}
	}
	
	final public function getUserByCode($appid, $secret, $code)
	{
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
		$json = file_get_contents($url);
		$arr = json_decode($json,true);
		return $arr;
	}
	
	final public function getWxUserInfo($openid, $access_token = '')
	{
		if($access_token == '')
		{
			$access_token = $this->access_token;
		}
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
		$json = file_get_contents($url);//获取微信用户基本信息
		$arr = json_decode($json,true);
		return $arr;
	}
	
	final public function parseurl($url = ""){
		$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
		return $url;
	}
	
	/**
	 * 获取AccessToken
	 * @return mixed
	 */
	final public function getAccessToken()
	{
	    $path = APP_PATH.'Weixin/Json/access_token.json';
	    $data = file_get_contents($path);
	    $data = json_decode($data, true);
	    $tempAccessToken = $data['access_token'];
	    if(!$data['access_token'] || $data['expire_time'] < time())
	    {
	        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret;
	        $result = $this->get_it($url);
	         
	        $token = json_decode($result, true);
	         
	        $tempAccessToken = $tempInfo['access_token'] = $token['access_token'];
	        $tempInfo['expires_in'] = time() + $token['expires_in'] - 200;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($tempInfo));
	        fclose($fp);
	    }
	    return $tempAccessToken;
	}
	
	/**
	 * 获取jsdk的ticket
	 */
	final public function getJsdk()
	{
	    //$this->getAccessToken();
	    $path = APP_PATH.'Weixin/Json/jsapi_ticket.json';
	    $data = file_get_contents($path);
	    $data = json_decode($data, true);
	    $jsapi_ticket = $data['jsapi_ticket'];
	    if(!$data['jsapi_ticket'] || $data['expire_time'] < time())
	    {
	        $access_token = $this->getAccessToken();
	        
	        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
	        $json = $this->get_it($url);
	        $arr = json_decode($json,true);
	        
	        $info['jsapi_ticket'] = $arr['ticket'];
	        $info['expire_time'] = time() + $arr['expires_in'] - 200;
	        $fp = fopen($path, "w");
	        fwrite($fp, json_encode($info));
	        fclose($fp);
	        $jsapi_ticket = $arr['ticket'];
	    }
	    
	    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	    $timestamp = time();
	    $nonceStr = $this->createNonceStr();
	    
	    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
	    $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
	    
	    $signature = sha1($string);
	    
	    $signPackage = array(
	        "appId"     => $this->appid,
	        "nonceStr"  => $nonceStr,
	        "timestamp" => $timestamp,
	        "url"       => $url,
	        "signature" => $signature,
	        "rawString" => $string
	    );
	    $this->assign('jsdk', json_encode($signPackage));
	}
	
	/**
	 * 用post方法获取数据
	 * @param $url
	 * @param $data
	 * @return
	 */
	public function post_it($url, $data)
	{
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	    curl_setopt($curl, CURLOPT_POST, 1);
	    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    $result = curl_exec($curl);
	    if(curl_errno($curl))
	    {
	        return 'Errno'.curl_error($curl);
	    }
	    curl_close($curl);
	    return $result;
	}
	
	/**
	 * 用get方法获取数据
	 * @param unknown $url
	 * @return mixed
	 */
	public function get_it($url)
	{
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    $result = curl_exec($ch);
	    return $result ;
	}
	
	/**
	 * jsdk获取字段
	 * @param number $length
	 * @return string
	 */
	private function createNonceStr($length = 16) {
	    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    $str = "";
	    for ($i = 0; $i < $length; $i++) {
	        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
	    }
	    return $str;
	}
	
	public function getPic($medias, $width = 600, $height = 400)
	{
	    $token = $this->getAccessToken();	     
	    $pictures = array();
	    $num = 1;
	    foreach($medias as $k => $v)
	    {
	        $media_id = $v;
	        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$media_id;
	        $img = $k.rand(0, 100).time().".jpg";
	        $img = $this->GrabImage($url, $img);
	        $temp = $img;
	        $yf_ex = explode("/", $temp);
	        $yf_ex[count($yf_ex)-1] = 'yf_'.$yf_ex[count($yf_ex)-1];
	        $dst_temp = implode("/", $yf_ex);
	        $this->mkThumbnail($temp, $width, $height, $dst_temp);
	        Yfimage::thumb2($temp, $dst_temp, '', $width, $height, true);
	        $thumb = str_replace('./', '/', $dst_temp);
	        $pictures['thumb'][] = $thumb;
	        if($num == 1)
	        {
	            $pictures['image'] = $thumb;
	            $num++;
	        }
	    }
	    return $pictures;
	}
	
	
	public function GrabImage($url, $filename = "") {
	    if($url == ""):return false;endif;
	    if($filename == "") {
	        $ext = strrchr($url, ".");
	        if($ext != ".gif" && $ext != ".jpg"):return false;endif;
	        $filename = date("YmdHis").$ext;
	    }
	    ob_start();
	    readfile($url);
	    $img = ob_get_contents();
	    ob_end_clean();
	    $size = strlen($img);
	    $yf_file = array('f', 'works', date('y'), date('m'), date('d'));
	    $file = './';
	    foreach($yf_file as $v)
	    {
	        $file .= $v.'/';
	        if(!is_dir($file))
	        {
				if (is_dir(base64_decode($file))) {
				    $yf_path = base64_decode($file);
				} else {
				    if (!mkdir($file)) {

				    }
				}
	        }
	    }
	    $file = $file.$filename;
	    $fp2 = @fopen($file, "a");
	    fwrite($fp2, $img);
	    fclose($fp2);
	    return $file;
	}
	
	function mkThumbnail($src, $width = null, $height = null, $filename = null) {
	    if (!isset($width) && !isset($height))
	        return false;
	    if (isset($width) && $width <= 0)
	        return false;
	    if (isset($height) && $height <= 0)
	        return false;
	
	    $size = getimagesize($src);
	
	
	    if (!$size)
	        return false;
	
	    list($src_w, $src_h, $src_type) = $size;
	    $src_mime = $size['mime'];
	    switch($src_type) {
	        case 1 :
	            $img_type = 'gif';
	            break;
	        case 2 :
	            $img_type = 'jpeg';
	            break;
	        case 3 :
	            $img_type = 'png';
	            break;
	        case 15 :
	            $img_type = 'wbmp';
	            break;
	        default :
	            return false;
	    }
	
	    if (!isset($width))
	        $width = $src_w * ($height / $src_h);
	    if (!isset($height))
	        $height = $src_h * ($width / $src_w);
	
	    $imagecreatefunc = 'imagecreatefrom' . $img_type;
	    $src_img = $imagecreatefunc($src);
	    $dest_img = imagecreatetruecolor($width, $height);
	    imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);
	
	    $imagefunc = 'image' . $img_type;
	    if ($filename) {
	        $imagefunc($dest_img, $filename);
	    } else {
	        header('Content-Type: ' . $src_mime);
	        $imagefunc($dest_img);
	    }
	    imagedestroy($src_img);
	    imagedestroy($dest_img);
	    return true;
	}
	
	public function jump($msg, $url)
	{
	    $this->display('Index/jump');
	    exit;
	}
	
}

?>